import { memo, useEffect, useState } from "react";
import { shallowEqual, useDispatch, useSelector } from "react-redux";
import { RootStateType } from "../../states";
import { useFetch_getProductsByType } from "../../service/product";
import { ProductType } from "../../types/product";
import ProductItem from "../productItem";
import {
  ErrorBlock,
  Grid,
  InfiniteScroll,
  PullToRefresh,
  Toast,
} from "antd-mobile";
import { useFetchGetOrganizations } from "../../service/organization";
import ProductListStyle from "./style";
import { PageType } from "../../constant";
import { setSearchValue, setSlectedTab } from "../../states/home";

const ProductList = memo(() => {
  const [hasMore, setHasMore] = useState(true);
  const [productsData, setProductsData] = useState<ProductType[]>([]);
  const [pageCount, setPageCount] = useState(1);
  const dispatch = useDispatch();

  const { data: orgsData, loading: getOrgsDataLoading } =
    useFetchGetOrganizations();
  const { getProductsByType, getProductsByTypeLoading } =
    useFetch_getProductsByType();

  const { selectedTab, searchValue } = useSelector(
    (state: RootStateType) => ({
      selectedTab: state.home.selectedTab,
      searchValue: state.home.searchValue,
    }),
    shallowEqual
  );
  useEffect(() => {
    if (getProductsByTypeLoading || getOrgsDataLoading) {
      Toast.show({
        icon: "loading",
        content: "加载中…",
        duration: 0,
      });
    } else {
      Toast.clear();
    }
  }, [getProductsByTypeLoading, getOrgsDataLoading]);

  useEffect(() => {
    if (selectedTab) {
      void getProductsByType(
        {
          pageSize: 10,
          pageNum: 1,
        },
        selectedTab,
        searchValue
      ).then(
        (res: { data: ProductType[]; page: PageType; message: string }) => {
          setProductsData(res.data);
          setPageCount(1);
          setHasMore(true);
        }
      );
    }
  }, [selectedTab, searchValue]);
  const pullRefetchHandel = async () => {
    try {
      await getProductsByType(
        {
          pageSize: 10,
          pageNum: 1,
        },
        selectedTab,
        searchValue
      );
    } catch (err) {
      Toast.show({
        icon: "fail",
        content: "刷新失败",
      });
    }
  };

  const loadMore = async () => {
    if (pageCount === 1) {
      setPageCount(pageCount + 1);
      return;
    }
    const res = (await getProductsByType(
      {
        pageSize: 10,
        pageNum: pageCount,
      },
      selectedTab,
      searchValue
    )) as { data: ProductType[] };
    if (res.data.length > 0) {
      setPageCount(pageCount + 1);
      setHasMore(true);
      setProductsData((value) => [...value, ...res.data]);
    } else {
      setHasMore(false);
    }
  };

  // 组件卸载时界面重置参数
  useEffect(() => {
    return () => {
      dispatch(setSearchValue(""));
      dispatch(setSlectedTab("all"));
    };
  }, []);

  return (
    <ProductListStyle className="ignore-productList">
      <PullToRefresh onRefresh={pullRefetchHandel}>
        {productsData.length > 0 ? (
          <>
            <Grid columns={2} gap={10}>
              {productsData.map((item) => (
                <Grid.Item span={1} key={item.id}>
                  <ProductItem data={item} key={item.id} orgsData={orgsData} />
                </Grid.Item>
              ))}
            </Grid>
            <InfiniteScroll
              loadMore={loadMore}
              hasMore={hasMore}
              threshold={100}
            />
          </>
        ) : (
          <ErrorBlock status="empty" />
        )}
      </PullToRefresh>
    </ProductListStyle>
  );
});

export default ProductList;
